/*
 * @Author: Cary
 * @Date: 2022-01-25 14:53:28
 * @FilePath: \alien-docse:\cary\vue-project\formdialog\src\lib\jscrypt.js
 */
import JSEncrypt from 'jsencrypt'

//  默认 私钥一般用于解密，（一般都是后端来做）
let pricateKey = '-----BEGIN RSA PRIVATE KEY-----MIICWwIBAAKBgQCD6t5ECGilAvPENqpLPU/UzmG6SDpkKWhCmp3EJMNaqUeFAVULveqN8SpIErGhfCBmFkNm+T5fZ9QtTQJgWtXPhd1dBJdoOy/778ZQIR2SUKUcuEPK2niZz6TaF9JJrf5b7Y2OHC/kyzS1EECDnD4dkJNWuWADIGtSHSH9S2muIwIDAQABAoGAEUjV5J4hb/WKERyEhaU774s3HNxX4kXWpltx7oBOpHNnrpK1HPu+XujJfHYOljUYXafvHu/rbz7Ae0sK06szNnSP0aNsD3yFav9vbcvzqs15jI07fnnkYaOzcMzn9lhR8wlaMzrGODMQXhGdFDzcFQk3/DX7iJ6PFIzcDLuuWDkCQQC5rsf6Ooky9v37zsfNlyOOszeUEB1sxXWDuXStYgbUWLNaPMt5FgsuqnWxtA3jdfC7DOfoA4ruLeXutbJRcQkvAkEAtd/Af/tqt1gZzWB3M9m00BDHsXPA0y+QNyNHl8pY1+jBfV3NAzug3q1VOPNghuVk/euiL4vpv9QXfF1mFYQFTQJAEh/SW0VtcPEU94hGjnXLPbmWmjg8dwqLHvFyRx5DZmTGFO/MOKSDMOnolRDrLiGr/sYSuN3nqLoIMJXBsxtidwJAJCHbwJFWVi5ukdrEU8zAm0V6Jsr0WABvCkU8B+/vTpWzOxDTlfzWrOaKs9HGL4aLVdbmVcPaIH4mXFLB4SxlUQJAVzfwLj7Gubljc0IqQB+iiNuuiNqEFeMSRXV9Ga9LrnUt+CvQutoj9cOBV+QprJSw/zeX1dl5UpIdyFYxD6r7QQ==-----END RSA PRIVATE KEY-----'

// 默认 公钥一般用于加密
let pubKey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCD6t5ECGilAvPENqpLPU/UzmG6SDpkKWhCmp3EJMNaqUeFAVULveqN8SpIErGhfCBmFkNm+T5fZ9QtTQJgWtXPhd1dBJdoOy/778ZQIR2SUKUcuEPK2niZz6TaF9JJrf5b7Y2OHC/kyzS1EECDnD4dkJNWuWADIGtSHSH9S2muIwIDAQAB-----END PUBLIC KEY-----'

/**
 * 对象加密字符串
 * @param {*} data 
 * @param {*} key 
 * @returns 
 */
export const encrypt = (data, key = pubKey) => {
  if (typeof data !== 'object') {
    throw new Error('请传入一个对象 {a: a}')
  }
  let encryptor = new JSEncrypt() // 创建加密对象实例
  //之前ssl生成的公钥，复制的时候要小心不要有空格
  let tpubKey = key
  encryptor.setPublicKey(tpubKey) //设置公钥
  return encryptor.encrypt(JSON.stringify(data)) // 对内容进行加密
}

/**
 * 对字符串解密
 * @param {*} data 
 * @param {*} key 
 * @returns 
 */
export const decrypt = (content, key = pricateKey) => {
  let encryptor = new JSEncrypt() // 创建加密对象实例
  let tpricateKey = key
  encryptor.setPublicKey(tpricateKey) //设置公钥
  return encryptor.decrypt(content) // 对内容进行加密
}

/**
 * 加密字符串
 * @param {*} data 
 * @param {*} key 
 * @returns 
 */
export const encryptStr = (data, key = pubKey) => {
  debugger
  if (typeof data !== 'string') {
    throw new Error('请传入一个字符串 string')
  }
  let encryptor = new JSEncrypt() // 创建加密对象实例
  //之前ssl生成的公钥，复制的时候要小心不要有空格
  let tpubKey = `-----BEGIN PUBLIC KEY-----${key}-----END PUBLIC KEY-----`
  encryptor.setPublicKey(tpubKey) //设置公钥
  return encryptor.encrypt(data) // 对内容进行加密
}
